package com.example.yang.yixin.Activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.example.yang.yixin.R;
import com.example.yang.yixin.Views.InputView;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.util.ArrayList;
import java.util.List;

public class InformationActivity extends BaseActivity {
    private String responseMsg = "";
    private static final int REQUEST_TIMEOUT = 5 * 1000;//设置请求超时10秒钟
    private static final int SO_TIMEOUT = 10 * 1000;  //设置等待数据超时时间10秒钟
    private InputView input_name, input_department, input_class, input_phonenumber;
    private RadioGroup radio_Group;
    private TextView input_username;
    private RadioButton radio_teacher, radio_student;
    public SharedPreferences pref;
    public SharedPreferences.Editor editor;
    private ImageView mIv_back;
    View view;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_information);
        pref = getSharedPreferences("user",MODE_PRIVATE);

        mIv_back=findViewById(R.id.iv_back);
        mIv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(InformationActivity.this,MeActivity.class);
                startActivity(intent);
            }
        });


        initView();
        boolean isremember = pref.getBoolean("rememberpass", false);
        if (isremember) {
            String name = pref.getString("input_name", "");
            String department = pref.getString("input_department", "");
            String classname = pref.getString("input_classname", "");
            String phonenumber = pref.getString("input_phonenumber", "");
            input_name.setText(name);
            input_department.setText(department);
            input_class.setText(classname);
            input_phonenumber.setText(phonenumber);

        }
        if(pref.getBoolean("condition",true)){
        Showhelpdailog();
        }

    }

    private void Showhelpdailog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("友课")
                .setIcon(R.mipmap.logo1)
                .setMessage(R.string.condition)
                .setPositiveButton("不再提示", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        editor=pref.edit();
                        editor.putBoolean("condition",false);
                        editor.apply();

                    }
                })
                .setNegativeButton("我知道了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.show();
    }

    private void initView() {
        initNarvBar(true, "个人信息", false);
        input_username = findViewById(R.id.input_username);
        input_name = findViewById(R.id.input_name);
        input_department = findViewById(R.id.input_department);
        input_class = findViewById(R.id.input_classname);
        input_phonenumber = findViewById(R.id.input_phonenumber);
        radio_teacher = (RadioButton) findViewById(R.id.ridio_teacher);
        radio_student = (RadioButton) findViewById(R.id.ridio_student);
        radio_Group = (RadioGroup) findViewById(R.id.radio_group);

        String username = getIntent().getStringExtra("data");
        input_username.setText(username);


    }

    public void OnSubmitClick(View view) {
        Thread Threadinformation = new Thread(new Threadinformation());
        Threadinformation.start();
    }

    private boolean loginServer(String username, String name, String college, String classname, String identity, String phonenumber) {
        boolean loginValidate = false;
        //使用apache HTTP客户端实现
        String urlStr = "http://47.106.141.161/MyFirstAndroidApp/UserServlet";
        HttpPost request = new HttpPost(urlStr);

        //如果传递参数多的话，可以对传递的参数进行封装
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        //添加用户名和密
        params.add(new BasicNameValuePair("username", username));
        params.add(new BasicNameValuePair("name", name));
        params.add(new BasicNameValuePair("college", college));
        params.add(new BasicNameValuePair("classname", classname));
        params.add(new BasicNameValuePair("identity", identity));
        params.add(new BasicNameValuePair("phonenumber", phonenumber));

        try {
            //设置请求参数
            request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

            HttpClient client = getHttpClient();
            //执行请求返回相应
            HttpResponse response = client.execute(request);

            //判断是否请求成功
            if (response.getStatusLine().getStatusCode() == 200) {
                loginValidate = true;
                //获得响应信息
                responseMsg = EntityUtils.toString(response.getEntity());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return loginValidate;
    }

    public HttpClient getHttpClient() {
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
        HttpClient client = new DefaultHttpClient(httpParams);
        return client;
    }


    Handler handler = new Handler()

    {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Snackbar.make(getWindow().getDecorView(),"保存失败，稍后再试！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    }).show();
                    break;
                case 2:
                    Snackbar.make(getWindow().getDecorView(),"好像断网了哦！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    }).show();
                    break;
                case 3:
                    Snackbar.make(getWindow().getDecorView(),"请完整填写您的信息哦！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    }).show();
                    break;
                case 4:
                    final ProgressDialog progressDialog = new ProgressDialog(InformationActivity.this);
                    progressDialog.setTitle("小依来报");
                    progressDialog.setMessage("努力记录中...");
                    progressDialog.setCancelable(false);
                    progressDialog.show();
                    new Thread() {
                        @Override
                        public void run() {
                            try {
                                super.run();
                                Thread.sleep(500);
                                progressDialog.dismiss();

                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }.start();

                    Snackbar.make(getWindow().getDecorView(),"保存成功，不能再修改哦！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    }).show();


                    break;
                case 5:
                    Snackbar.make(getWindow().getDecorView(),"无法修改已保存的信息哦！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    }).show();
                    break;
            }

        }
    };

    class Threadinformation implements Runnable {

        @Override
        public void run() {
            String identity = null;
            String username = input_username.getText().toString();
            String name = input_name.getInputStr();
            String college = input_department.getInputStr();
            String classname = input_class.getInputStr();
            String phonenumber = input_phonenumber.getInputStr();

            editor = pref.edit();
            editor.putBoolean("rememberpass", true);
            editor.putString("input_name", name);
            editor.putString("input_department", college);
            editor.putString("input_classname", classname);
            editor.putString("input_phonenumber", phonenumber);


            if (radio_teacher.isChecked()) {
                identity = radio_teacher.getText().toString();

            } else {
                identity = radio_student.getText().toString();

            }
            Message msg = handler.obtainMessage();
            if (pref.getString("input_name","").equals("")) {
                if ((name.equals("")) || (classname.equals("")) || (college.equals("")) || (identity.equals("") || (phonenumber.equals("")))) {
                    msg.what = 3;
                    handler.sendMessage(msg);
                } else {
                    //URL合法，但是这一步并不验证密码是否正确
                    boolean loginValidate = loginServer(username, name, college, classname, identity, phonenumber);


                    if (loginValidate) {
                        if (responseMsg.equals("")) {
                            msg.what = 4;
                            handler.sendMessage(msg);
                            editor.putBoolean("saved",false);
                            editor.apply();

                        } else {
                            msg.what = 1;
                            handler.sendMessage(msg);
                        }

                    } else {
                        msg.what = 2;
                        handler.sendMessage(msg);
                    }
                }
            }else{
                msg.what=5;
                handler.sendMessage(msg);
            }
        }
    }


}
